package myPetStore.web.servlet;

import myPetStore.domain.Product;
import myPetStore.service.CatalogService;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class FloatingWindowServlet extends HttpServlet
{
    private CatalogService catalogService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        String categoryId = req.getParameter("categoryId");
        catalogService = new CatalogService();
        List<Product> productList = catalogService.getProductListByCategory(categoryId);
        JSONArray jsonArray = new JSONArray();
        int i = 0;
        while (i < productList.size())
        {
            Product product = productList.get(i);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", product.getName());
            String description = product.getDescription();
            int beginIndex = description.indexOf('>') + 1;
            jsonObject.put("description", description.substring(beginIndex));
            jsonObject.put("src", "images/" + product.getName() + ".jpg");
            jsonArray.add(jsonObject);
            i++;
        }

        resp.setContentType("text/json");
        PrintWriter out = resp.getWriter();
        out.write(jsonArray.toString());
    }
}
